// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// a [author] rhyme_lph
// D [email]  rhymelph@gmail.com
// E [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/invoice_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/product_entity.dart';
import 'package:finance_app/src/http_service/http_inventory_service.dart';
import 'package:finance_app/src/mixin/from_attach_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/calendar_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';

class AdjustInventoryProvider extends BaseProvider with FormAttachMixin {
  TextEditingController additionalController = TextEditingController();
  FocusNode additionalFocusNode = FocusNode();
  List<OcrAttachmentEntity> attachedFiles;

  int initQuantity;
  int updateQuantity;
  int id;
  InvoiceEntity invoiceEntity;
  DateTime date = DateTime.tryParse(Config.currentFY.startDate);

  @override
  Future get dataFuture => null;

  String currentSelect = 'Stock Adjustment';

  @override
  void dispose() {
    super.dispose();
    additionalController.dispose();
    additionalFocusNode.dispose();
  }

  void onSave() async {
    ProductEntity entity;
    String type = currentSelect == 'Stock Adjustment' ? 'adjust' : 'return';
    if (type == 'return' && updateQuantity < initQuantity) {
      return;
    }

    List<int> attachmentIds = await uploadFiles();
    if (attachmentIds == null) return;

    await post(
        HttpInventoryService.updateInventory(
          id,
          type: type,
          quantity: updateQuantity,
          issued_at: DateTimeUtils.formatDateTime(date, 'yyyy-MM-dd'),
          attachment_ids: attachmentIds,
        ),
        loadingTip: S.current.loading,
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      entity = getEntityFromResult<ProductEntity>(result);
    });
    if (entity != null) {
      obtainContext?.call((context) async {
        await showAdjustedInventorySuccessBottomSheet(context);
        Navigator.of(context).pop(entity);
      });
    }
  }

  void onChangeSelect(String e) {
    if (currentSelect == e) return;
    currentSelect = e;
    update();
  }

  void onChangeNumber(int value) {
    updateQuantity = value;
    update();
  }

  void onSelectInvoice() async {
    final result =
        await Routes.navigateTo(RouterGenProviders.invoiceNumberPage, params: {
      'isMultiple': false,
    });

    if (result != null) {
      invoiceEntity = result;
      update();
    }
  }

  void onChangeIssueDate() {
    FocusManager.instance.primaryFocus.unfocus();
    obtainContext?.call((context) async {
      date = await showCalendarBottomSheet(context, date);
      update();
    });
  }

  @override
  List<OcrAttachmentEntity> get attachments => attachedFiles;

  @override
  bool get isEdit => true;

  @override
  void unFocus() {
    FocusManager.instance.primaryFocus.unfocus();
  }
}
